<template>
  <view class="bg-gray-50 w-[750rpx] pb-[150rpx] box-border bgs">
    <!-- 顶部导航 -->
    <view class="bg-gradient-to-r from-blue-600 to-blue-800 text-white p-[30rpx] sticky top-0 z-100 flex justify-between items-center shadow-lg">
      <IconFont name="arrow-left" class="text-[40rpx] cursor-pointer" @click="handleBack" />
      <text class="text-[36rpx] font-bold flex-1 text-center">发布任务</text>
      <view></view>
    </view>

    <!-- 悬赏类型选择 -->
    <view class="bg-white rounded-[25rpx] p-[40rpx] m-[30rpx] shadow-lg box-border">
      <view class="text-[34rpx] font-bold text-gray-800 mb-[30rpx] flex items-center">
        <!-- <IconFont name="tasks" class="text-blue-500 mr-[15rpx]" /> -->
        <text>选择任务类型</text>
      </view>
      
      <view class="grid grid-cols-3 gap-[30rpx] text-[24rpx]">
        <view 
          v-for="(type, index) in bountyTypes" 
          :key="index"
          class="rounded-[20rpx] p-[25rpx] text-center cursor-pointer transition-all border-2"
          :class="selectedType === type.value ? 'bg-blue-50 border-blue-500' : 'bg-gray-50 border-transparent'"
          @tap="selectType(type.value)"
        >
          <!-- <IconFont :name="type.icon" class="text-[50rpx] text-blue-500 mb-[20rpx]" /> -->
          <text :class="selectedType === type.value ? 'text-blue-600 font-bold block' : 'text-gray-800 font-bold block'">{{ type.name }}</text>
        </view>
      </view>
      
      <!-- 招聘类型选择 -->
      <view v-if="selectedType === 'recruit'" class="mt-[40rpx]">
        <text class="text-[28rpx] font-medium mb-[20rpx] block">选择招聘类型</text>
        <view class="flex gap-[20rpx] text-[24rpx]">
          <view 
            v-for="(recruitType, index) in recruitTypes" 
            :key="index"
            class="flex-1 rounded-[20rpx] p-[25rpx] text-center cursor-pointer transition-all border-2"
            :class="selectedRecruitType === recruitType.value ? 'bg-blue-50 border-blue-500' : 'bg-gray-50 border-transparent'"
            @tap="selectRecruitType(recruitType.value)"
          >
            <!-- <IconFont :name="recruitType.icon" class="text-[50rpx] text-blue-500 mb-[20rpx]" /> -->
            <text :class="selectedRecruitType === recruitType.value ? 'text-blue-600 font-bold block' : 'text-gray-800 font-bold block'">{{ recruitType.name }}</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 悬赏表单 -->
    <view class="bg-white rounded-[25rpx] p-[40rpx] m-[30rpx] shadow-lg box-border">
      <view class="text-[34rpx] font-bold text-gray-800 mb-[30rpx] flex items-center">
        <!-- <IconFont name="edit" class="text-blue-500 mr-[15rpx]" /> -->
        <text>悬赏任务信息</text>
      </view>
      
      <nut-form ref="formRef" :model="formData">
        <!-- 任务标题 -->
        <view class="mb-[40rpx]">
          <text class="text-[30rpx] font-bold mb-[20rpx] block text-gray-800">任务标题</text>
          <input 
            v-model="formData.title"
            type="text" 
            class="w-full p-[25rpx] border-2 border-gray-200 rounded-[15rpx] text-[28rpx] bg-gray-50 box-border"
            placeholder="请输入任务标题（50字以内）"
          />
        </view>

        <!-- 任务分类 -->
        <view class="mb-[40rpx]">
          <text class="text-[30rpx] font-bold mb-[20rpx] block text-gray-800">任务分类</text>
          <view class="w-full p-[25rpx] border-2 border-gray-200 rounded-[15rpx] text-[28rpx] bg-gray-50 box-border" @click="showCategoryPicker = true">
            {{ getCategoryText(formData.category) || '请选择任务分类' }}
          </view>
          <nut-popup v-model:visible="showCategoryPicker" position="bottom" round>
            <nut-picker
              v-model="categoryValue"
              :columns="categoryOptions"
              title="请选择任务分类"
              @confirm="onCategoryConfirm"
              @cancel="showCategoryPicker = false"
            />
          </nut-popup>
        </view>

        <!-- 任务描述 -->
        <view class="mb-[40rpx]">
          <text class="text-[30rpx] font-bold mb-[20rpx] block text-gray-800">任务描述</text>
          <textarea 
            v-model="formData.description"
            style="height: 100%;"
            class="w-full p-[25rpx] border-2 border-gray-200 rounded-[15rpx] text-[28rpx] bg-gray-50 min-h-[120rpx] max-h-[400rpx] box-border resize-none"
            placeholder="请详细描述任务要求、完成标准、注意事项等"
          />
        </view>

        <!-- 截止日期 -->
        <view class="mb-[40rpx]">
          <text class="text-[30rpx] font-bold mb-[20rpx] block text-gray-800">截止日期</text>
          <view class="w-full p-[25rpx] border-2 border-gray-200 rounded-[15rpx] text-[28rpx] bg-gray-50 box-border" @click="showDatePicker = true">
            {{ formData.deadline ? formatDate(formData.deadline) : '请选择任务截止日期' }}
          </view>
          <picker mode="date" :value="formData.deadline || todayStr" @change="onDeadlinePickerChange">
            <view class="hidden"></view>
          </picker>
        </view>

        <!-- 任务地点 -->
        <view class="mb-[40rpx]">
          <text class="text-[30rpx] font-bold mb-[20rpx] block text-gray-800">任务地点</text>
          <input 
            v-model="formData.location"
            type="text" 
            class="w-full p-[25rpx] border-2 border-gray-200 rounded-[15rpx] text-[28rpx] bg-gray-50 box-border"
            placeholder="线上任务请填写'线上'，线下任务请填写具体地址"
          />
        </view>
      </nut-form>
    </view>

    <!-- 阶段悬赏设置 -->
    <view class="bg-white rounded-[25rpx] p-[40rpx] m-[30rpx] shadow-lg box-border">
      <view class="flex justify-between items-center mb-[30rpx]">
        <text class="text-[32rpx] font-bold text-gray-800">阶段任务设置</text>
        <nut-button 
          type="primary" 
          size="small"
          class="px-[30rpx] py-[15rpx] text-[26rpx]"
          @click="addStage"
        >
          <IconFont name="plus" class="mr-[10rpx]" />
          添加阶段
        </nut-button>
      </view>
      
      <view 
        v-for="(stage, index) in stages" 
        :key="index"
        class="bg-gray-50 rounded-[20rpx] p-[30rpx] mb-[30rpx] relative"
      >
        <view class="flex justify-between items-center mb-[20rpx]">
          <text class="text-[30rpx] font-bold text-gray-800">第{{ index + 1 }}阶段</text>
          <IconFont 
            v-if="stages.length > 1"
            name="trash-alt" 
            class="text-[36rpx] text-red-500 cursor-pointer"
            @click="removeStage(index)"
          />
        </view>
        
        <view class="flex items-center mb-[20rpx]">
          <text class="text-[28rpx] text-gray-600 mr-[20rpx] w-[150rpx]">阶段金额</text>
          <input 
            v-model="stage.amount"
            type="number" 
            class="flex-1 p-[20rpx] border-2 border-gray-200 rounded-[15rpx] text-[28rpx] bg-white box-border"
            placeholder="0"
            min="0"
            @input="calculateTotal"
          />
        </view>
        
        <view class="mt-[20rpx]">
          <text class="text-[28rpx] font-medium mb-[15rpx] block">阶段描述</text>
          <input 
            v-model="stage.description"
            type="text" 
            class="w-full p-[20rpx] border-2 border-gray-200 rounded-[15rpx] text-[28rpx] bg-white box-border"
            placeholder="请描述本阶段任务要求"
          />
        </view>
        
        <view v-if="index < stages.length - 1" class="text-center mt-[20rpx] relative">
          <view class="absolute top-1/2 left-0 right-0 h-[2rpx] bg-gray-200 z-1"></view>
          <text class="bg-white px-[20rpx] relative z-2 text-gray-500 text-[26rpx]">+</text>
        </view>
      </view>
    </view>

    <!-- 金额总计 -->
    <view class="bg-gradient-to-r from-blue-600 to-blue-800 text-white rounded-[25rpx] p-[30rpx] m-[30rpx] flex justify-between items-center box-border">
      <text class="text-[32rpx] font-bold">任务总金额</text>
      <text class="text-[48rpx] font-bold">¥ {{ totalAmount }}</text>
    </view>

    <!-- 服务方选择 -->
    <view class="bg-white rounded-[25rpx] p-[40rpx] m-[30rpx] shadow-lg mb-[30rpx] box-border">
      <view class="text-[32rpx] font-bold mb-[30rpx] flex items-center">
        <!-- <IconFont name="users" class="text-[#2196F3] mr-[15rpx]" /> -->
        <text>服务方选择</text>
      </view>
      <!-- 单选框组 -->
      <nut-radio-group v-model="providerType" direction="horizontal" class="gap-x-[40rpx] mb-[30rpx] flex items-center">
        <nut-radio :label="'all'" class="text-[28rpx] !text-[#2196F3] flex items-center">不限</nut-radio>
        <nut-radio :label="'person'" class="text-[28rpx] !text-[#2196F3] flex items-center">个人从业者</nut-radio>
        <nut-radio :label="'company'" class="text-[28rpx] !text-[#2196F3] flex items-center">服务商</nut-radio>
      </nut-radio-group>
      
      <!-- 服务商列表 -->
      <view v-if="providerType === 'all' || providerType === 'company'">
        <view class="text-[28rpx] font-medium my-[20rpx]">可选服务商</view>
        <view class="grid grid-cols-2 gap-[20rpx]">
          <view v-for="company in companyList" :key="company.id" class="flex items-center bg-gray-50 rounded-[15rpx] p-[20rpx] border-2 transition-all border-transparent hover:border-[#2196F3]">
            <nut-checkbox :model-value="selectedCompanies.includes(company.id)" @update:model-value="val => handleCompanyCheck(val, company.id)" class="mr-[15rpx] !text-[#2196F3]" />
            <IconFont name="building" class="text-[36rpx] text-[#2196F3] mr-[10rpx]" />
            <view class="flex-1 min-w-0">
              <text class="text-[28rpx] font-bold text-gray-800 truncate block">{{ company.name }}</text>
              <text class="block text-[24rpx] text-gray-500 truncate">{{ company.desc }}</text>
            </view>
          </view>
        </view>
      </view>
      <!-- 个人从业者列表 -->
      <view v-if="providerType === 'all' || providerType === 'person'">
        <view class="text-[28rpx] font-medium my-[20rpx]">可选个人从业者</view>
        <view class="grid grid-cols-2 gap-[20rpx] mb-[20rpx]">
          <view v-for="person in personList" :key="person.id" class="flex items-center bg-gray-50 rounded-[15rpx] p-[20rpx] border-2 transition-all border-transparent hover:border-[#2196F3]">
            <nut-checkbox :model-value="selectedPersons.includes(person.id)" @update:model-value="val => handlePersonCheck(val, person.id)" class="mr-[15rpx] !text-[#2196F3]" />
            <IconFont name="user" class="text-[36rpx] text-[#2196F3] mr-[10rpx]" />
            <view class="flex-1 min-w-0">
              <text class="text-[28rpx] font-bold text-gray-800 truncate block">{{ person.name }}</text>
              <text class="block text-[24rpx] text-gray-500 truncate">{{ person.desc }}</text>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 区域选择 -->
    <view class="bg-white p-[40rpx] m-[30rpx] box-border">
      <view class="text-[32rpx] font-bold mb-[36rpx]">区域选择</view>
      <nut-radio-group v-model="regionLevel" direction="vertical" class="w-full">
        <view v-for="item in regionOptions" :key="item.value"
          class="flex items-center py-[20rpx] border-b border-gray-200 last:border-b-0 cursor-pointer select-none text-[28rpx] transition-all"
        >
          <nut-radio :label="item.value" class="mr-[24rpx] text-blue-600 flex items-center" />
          <text :class="regionLevel === item.value ? 'text-blue-600 font-bold' : 'text-gray-500'">{{ item.label }}</text>
          <text class="ml-1 text-gray-400">（信息费{{ item.fee }}元）</text>
        </view>
      </nut-radio-group>
      <view class="text-[28rpx] mt-[24rpx]">
        当前选择：{{ getRegionText(regionLevel as string) }}，信息费¥{{ regionFeeMap[regionLevel] }}
      </view>
    </view>

    <!-- 支付按钮 -->
    <view class="bg-white rounded-[25rpx] p-[40rpx] m-[30rpx] shadow-lg text-center box-border">
      <nut-button 
        type="primary" 
        size="large"
        class="w-full text-[36rpx] font-bold bg-gradient-to-r from-orange-400 to-red-500 h-[96rpx]"
        @click="handlePayment"
      >
        <IconFont name="lock" class="mr-[15rpx]" />
        支付任务金额并发布
      </nut-button>
      <text class="text-[26rpx] text-gray-600 mt-[30rpx] block">
        支付后金额将托管在平台，任务完成后支付给执行方
      </text>
    </view>

    <!-- 流程说明 -->
    <view class="bg-white rounded-[25rpx] p-[40rpx] m-[30rpx] shadow-lg box-border">
      <text class="text-[32rpx] font-bold text-gray-800 mb-[30rpx] text-center block">任务流程说明</text>
      
      <view class="flex flex-col gap-[30rpx]">
        <view 
          v-for="(step, index) in processSteps" 
          :key="index"
          class="flex items-start"
        >
          <view class="w-[50rpx] h-[50rpx] bg-blue-500 text-white rounded-full flex items-center justify-center text-[30rpx] font-bold mr-[20rpx] flex-shrink-0">
            {{ index + 1 }}
          </view>
          <view class="flex-1">
            <text class="text-[30rpx] font-bold text-gray-800 mb-[10rpx] block">{{ step.title }}</text>
            <text class="text-[26rpx] text-gray-600 leading-[1.5]">{{ step.desc }}</text>
          </view>
        </view>
      </view>
      
      <view class="bg-yellow-50 border-l-5 border-yellow-400 p-[20rpx] rounded-[10rpx] mt-[20rpx] text-[26rpx] text-gray-600">
        <IconFont name="exclamation-circle" class="text-yellow-400 mr-[10rpx]" />
        如出现纠纷：任何一方可点击"我有异议"，平台将冻结该笔交易金额，双方协商一致后解锁交易并按流程核销。
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import Taro from '@tarojs/taro'
import { Radio as nutRadio, RadioGroup as nutRadioGroup, Checkbox as nutCheckbox } from '@nutui/nutui-taro'

// 悬赏类型
const bountyTypes = ref([
  { name: '日结类', value: 'daily', icon: 'calendar-day' },
  { name: '悬赏类', value: 'bounty', icon: 'award' },
  { name: '招聘类', value: 'recruit', icon: 'briefcase' }
])

// 招聘类型
const recruitTypes = ref([
  { name: '工厂类', value: 'factory', icon: 'industry' },
  { name: '特殊类', value: 'special', icon: 'star' }
])

// 任务分类选项
const categoryOptions = ref([
  { text: '设计类', value: 'design' },
  { text: '技术开发', value: 'tech' },
  { text: '内容创作', value: 'content' },
  { text: '推广营销', value: 'promotion' },
  { text: '数据录入', value: 'data' },
  { text: '其他', value: 'other' }
])

// 流程步骤
const processSteps = ref([
  { title: '发布任务', desc: '填写任务信息并支付任务金额到平台' },
  { title: '执行方申请', desc: '平台从业者在线申请执行任务' },
  { title: '选择执行方', desc: '您可以选择申请者或邀请特定从业者' },
  { title: '开始执行', desc: '双方同意后正式开始执行任务' },
  { title: '阶段结算', desc: '每个阶段完成后单独结算该阶段金额' }
])

// 选中状态
const selectedType = ref('daily')
const selectedRecruitType = ref('')

// 表单数据
const formData = reactive({
  title: '',
  category: '',
  description: '',
  deadline: '',
  location: ''
})

// 阶段数据
const stages = ref([
  { amount: 0, description: '' },
  { amount: 0, description: '' },
  { amount: 0, description: '' }
])

// 计算总金额
const totalAmount = computed(() => {
  return stages.value.reduce((total, stage) => {
    return total + (parseFloat(stage.amount) || 0)
  }, 0).toFixed(2)
})

// 选择类型
const selectType = (type: string) => {
  selectedType.value = type
}

// 选择招聘类型
const selectRecruitType = (type: string) => {
  selectedRecruitType.value = type
}

// 添加阶段
const addStage = () => {
  stages.value.push({ amount: 0, description: '' })
}

// 删除阶段
const removeStage = (index: number) => {
  if (stages.value.length > 1) {
    stages.value.splice(index, 1)
  } else {
    Taro.showToast({
      title: '至少需要保留一个阶段',
      icon: 'none'
    })
  }
}

// 计算总金额
const calculateTotal = () => {
  // 触发计算，computed会自动更新
}

// 返回
const handleBack = () => {
  Taro.navigateBack()
}

/**
 * 服务方类型
 * @type {import('vue').Ref<'all'|'person'|'company'>}
 */
const providerType = ref<'all'|'person'|'company'>('all')

/**
 * 个人从业者模拟数据
 * @type {Array<{id: string, name: string, desc: string}>}
 */
const personList = ref([
  { id: 'p1', name: '张三', desc: 'UI设计师 5年经验' },
  { id: 'p2', name: '李四', desc: '前端开发 3年经验' },
  { id: 'p3', name: '王五', desc: '文案策划 4年经验' },
  { id: 'p4', name: '赵六', desc: '市场推广 2年经验' }
])

/**
 * 服务商模拟数据
 * @type {Array<{id: string, name: string, desc: string}>}
 */
const companyList = ref([
  { id: 'c1', name: '蓝色科技', desc: '专业软件开发' },
  { id: 'c2', name: '创意设计坊', desc: '品牌设计与包装' },
  { id: 'c3', name: '推广大师', desc: '全渠道推广' },
  { id: 'c4', name: '数据录入中心', desc: '数据处理服务' }
])

/**
 * 选中的个人从业者ID
 * @type {import('vue').Ref<string[]>}
 */
const selectedPersons = ref<string[]>([])
/**
 * 选中的服务商ID
 * @type {import('vue').Ref<string[]>}
 */
const selectedCompanies = ref<string[]>([])

/**
 * 区域选择
 * @type {import('vue').Ref<string>}
 */
const regionLevel = ref('city')
/** 区域信息费映射 */
const regionFeeMap: Record<string, number> = {
  city: 1,
  province: 5,
  nation: 8
}
/**
 * 区域选项
 * @type {Array<{value: string, label: string, fee: number}>}
 */
const regionOptions: Array<{ value: string, label: string, fee: number }> = [
  { value: 'city', label: '市级', fee: 1 },
  { value: 'province', label: '省级', fee: 5 },
  { value: 'nation', label: '全国', fee: 8 }
]
/**
 * 获取区域文本
 * @param {any} val
 * @returns {string}
 */
function getRegionText(val: any) {
  if (val === 'city') return '市级'
  if (val === 'province') return '省级'
  if (val === 'nation') return '全国'
  return ''
}

// 支付
const handlePayment = () => {
  if (!formData.title) {
    Taro.showToast({
      title: '请填写任务标题',
      icon: 'none'
    })
    return
  }
  
  if (!formData.category) {
    Taro.showToast({
      title: '请选择任务分类',
      icon: 'none'
    })
    return
  }
  
  if (!formData.description) {
    Taro.showToast({
      title: '请填写任务描述',
      icon: 'none'
    })
    return
  }
  
  const total = parseFloat(totalAmount.value)
  if (total <= 0) {
    Taro.showToast({
      title: '请设置任务金额',
      icon: 'none'
    })
    return
  }
  // 打印选中的服务方
  console.log('选中的个人从业者:', selectedPersons.value)
  console.log('选中的服务商:', selectedCompanies.value)
  // 打印区域选择和信息费
  console.log('区域选择:', getRegionText(regionLevel.value), '信息费:', regionFeeMap[regionLevel.value])
  Taro.showModal({
    title: '确认发布',
    content: `任务标题：${formData.title}\n总金额：¥${totalAmount.value}`,
    success: (res) => {
      if (res.confirm) {
        Taro.showToast({
          title: `任务发布成功！总金额：¥${totalAmount.value}，即将跳转到支付页面...`,
          icon: 'success',
          duration: 3000
        })
      }
    }
  })
}

const showCategoryPicker = ref(false)
const categoryValue = ref<string[]>([])
function onCategoryConfirm(val: any) {
  showCategoryPicker.value = false
  formData.category = val[0]?.value || ''
}
function getCategoryText(val: string) {
  const found = categoryOptions.value.find((item: any) => item.value === val)
  return found ? found.text : ''
}
// 获取当前日期字符串（格式：YYYY-MM-DD）
function getTodayString(): string {
  const today = new Date()
  const year = today.getFullYear()
  const month = String(today.getMonth() + 1).padStart(2, '0')
  const day = String(today.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}

const showDatePicker = ref(false)
const dateValue = ref('')
const todayStr = getTodayString()

// 使用默认起止日期
function onCalendarChoose(val: any) {
  showDatePicker.value = false
  let dateStr = ''
  
  if (typeof val === 'string') {
    dateStr = val
  } else if (Array.isArray(val) && val.length >= 3) {
    const year = String(val[0])
    const month = String(val[1]).padStart(2, '0')
    const day = String(val[2]).padStart(2, '0')
    dateStr = `${year}-${month}-${day}`
  } else if (val && typeof val === 'object') {
    if (val.year && val.month && val.day) {
      const year = val.year
      const month = String(val.month).padStart(2, '0')
      const day = String(val.day).padStart(2, '0')
      dateStr = `${year}-${month}-${day}`
    }
  }
  
  if (dateStr) {
    formData.deadline = dateStr
    dateValue.value = dateStr
  }
}

// 格式化日期字符串
function formatDate(val: any) {
  if (!val) return ''
  if (typeof val === 'string') {
    if (/^\d{4}-\d{2}-\d{2}$/.test(val)) return val
    if (/^\d{4}\/\d{2}\/\d{2}$/.test(val)) return val.replace(/\//g, '-')
    return val
  }
  if (val && typeof val === 'object' && Array.isArray(val.selectedValue)) {
    return val.selectedValue.join('-')
  }
  return ''
}

const handlePersonCheck = (val: boolean, id: string) => {
  const idx = selectedPersons.value.indexOf(id)
  if (val && idx === -1) selectedPersons.value.push(id)
  if (!val && idx !== -1) selectedPersons.value.splice(idx, 1)
}
const handleCompanyCheck = (val: boolean, id: string) => {
  const idx = selectedCompanies.value.indexOf(id)
  if (val && idx === -1) selectedCompanies.value.push(id)
  if (!val && idx !== -1) selectedCompanies.value.splice(idx, 1)
}
defineExpose({ handlePersonCheck, handleCompanyCheck })
</script>

<style lang="scss">
.bgs {
  .nut-cell-group__wrap{
    box-shadow: none !important;
  }
}
</style>